package com.free.bsf.health.memoryParse;

import lombok.Data;
import lombok.val;

import java.lang.reflect.Array;
import java.util.*;

/**
 * @Classname ObjParser
 * @Description 对象解析
 * @Date 2021/6/7 11:58
 * @Created by chejiangyi
 */
public class ObjParser {
    public ObjInfo parse(Object obj){
        ObjInfo info = new ObjInfo();
        info.setCls(obj.getClass());
        if (obj.getClass().isArray()) {
            val size = Array.getLength(obj);
            val list = new ArrayList<>(size);
            info.setObjs(list);
            for(int i=0;i<size;i++){
                Object o =Array.get(obj, i);
                if(o!=null&&!o.getClass().isPrimitive()) {
                    info.setCls(o.getClass());
                    list.add(o);
                }
            }
        } else if (obj instanceof Collection) {
            Collection result2 = ((Collection) obj);
            val list = new ArrayList<>(result2.size());
            info.setObjs(list);
            for(Object o:result2){
                if(o!=null&&!o.getClass().isPrimitive()){
                    info.setCls(o.getClass());
                    list.add(o);
                }
            }
        }else if(obj instanceof Map){
            Map result2 = ((Map) obj);
            val list = new ArrayList<>(result2.size());
            info.setObjs(list);
            for(Object o:result2.entrySet()){
                if(o!=null){
                    info.setCls(o.getClass());
                    list.add(o);
                }
            }
        }
        else {
            info.setCls(obj.getClass());
            val list = new ArrayList<>(1);
            info.setObjs(list);
            list.add(obj);
        }
        return info;
    }
    @Data
    public static class ObjInfo{
         Class cls;
         List objs;

         public void clear(){
             this.getObjs().clear();
             cls=null;
         }
    }
}
